package net.htjs.juc.sleepwait;

import lombok.extern.slf4j.Slf4j;

/**
 * sleep和 wait 的区别
 * 1.sleep是 Thread类的静态方法，wait是object的方法
 * 2.sleep使用的时候不强制使用synchronized方法，wait使用必须强制使用synchronized方法
 * 3.sleep睡眠时间不会释放锁，wait等待期间会释放锁
 * 4.他们的状态都是一样的TIMED_WAITING
 * */
@Slf4j
public class Demo4 {

    static final Object room = new Object();
    static boolean hasCigarette = false;
    static boolean hasTakeout =  false;

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            synchronized (room) {
                log.info("有烟没:[{}]", hasCigarette);
                if(!hasCigarette) {
                    log.info("没烟，先歇会儿");
                    try {
                        room.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.info("有烟没:[{}]", hasCigarette);
                if (hasCigarette) {
                    log.info("有烟了，可以开始干活了");
                } else {
                    log.info("没干成活");
                }
            }
        }, "小南").start();

        new Thread(() -> {
            synchronized (room) {
                Thread thread = Thread.currentThread();
                log.info("外卖送到没?[{}]", hasTakeout);
                if(!hasTakeout) {
                    log.info("没外卖，先歇会");
                    try {
                        room.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.info("外卖送到没?[{}]", hasTakeout);
                if(hasTakeout) {
                    log.info("外卖送到了，可以开始干活了");
                } else {
                    log.info("没干成活");
                }
            }
        }, "小女").start();

        Thread.sleep(1000);

        new Thread(() -> {
            synchronized (room) {
                hasTakeout = true;
                log.info("外卖到了");
                //错误唤醒(虚假唤醒)
                //room.notify();
                room.notifyAll();
            }
        }, "送外卖的").start();
    }

}
